﻿//----------------------------------------------------------
// @author: Icinetic TIC SL
//----------------------------------------------------------

var errorPage;

//----------------------------------------------------------
// Common
//----------------------------------------------------------

function ResetForm(formId) {
    $(':input', '#' + formId)
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');
}

function ConfirmDialog(settings) {
    $("body").append('<div id="dialog-confirm" title="' + settings['title'] + '">' + settings['message'] + '</div>');

    var btns = {};

    btns[$.uiLocale['common']['accept']] = function () {
        if (settings["funcOK"] != undefined)
            settings["funcOK"]();
        $(this).remove();
    };

    btns[$.uiLocale['common']['cancel']] = function () {
        if (settings["funcCancel"] != undefined)
            settings["funcCancel"]();
        $(this).remove();
    };

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        autoResize: true,
        resizable: false,
        buttons: btns,
        open: function () {
            $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                icons: { primary: 'ok-button' }
            });
            $(this).parent().find('.ui-dialog-buttonpane button:first-child').next().button({
                icons: { primary: 'close-button' }
            });
            $("#dialog-confirm").parent().find(".ui-button").blur();
        },
        close: function (ev, ui) {
            if (settings["funcCancel"] != undefined)
                settings["funcCancel"]();
            $(this).remove();
        }
    });
}

function CancelChangesAndRedirect(url) {
    var settings = {
        title: $.uiLocale['cancelChangesDialog']['title'],
        message: $.uiLocale['cancelChangesDialog']['message'],
        funcOK: function () {
            document.location = url;
        }
    };

    ConfirmDialog(settings);

    return false;
}

function SelectionPopUp(settings) {
    var btns = {};

    btns[$.uiLocale['common']['select']] = function () {
        if (settings["funcOK"] != undefined)
            settings["funcOK"]();
        $(this).dialog("destroy");
    };

    btns[$.uiLocale['common']['cancel']] = function () {
        if (settings["funcCancel"] != undefined)
            settings["funcCancel"]();
        $(this).dialog("destroy");
    };

    var popUpId = settings['popUpId'];
    $('#' + popUpId).attr('title', $.uiLocale['selectionDialog']['title']);

    $("#" + popUpId).dialog({
        resizable: false,
        modal: true,
        buttons: btns,
        open: function () {
            $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                icons: { primary: 'select-button' }
            });
            $(this).parent().find('.ui-dialog-buttonpane button:first-child').next().button({
                icons: { primary: 'close-button' }
            });
            $("#" + popUpId).parent().find(".ui-button").blur();

            if (settings['openFunc'] != undefined) {
                settings['openFunc']();
            };
        },
        width: settings['width'] || 300,
        close: function (ev, ui) {
            if (settings["funcCancel"] != undefined)
                settings["funcCancel"]();
            $(this).dialog("destroy");
        }
    });
}

function DefaultAddOrDetailPopUpEventTriggers(dialogId) {
    $("#" + dialogId).bind("keypress", function (e) {
        if (e.keyCode == 13) {
            var buttons = $("#" + dialogId).dialog('option', 'buttons');

            if (buttons[$.uiLocale['common']['save']] != undefined) {
                buttons[$.uiLocale['common']['save']]();
            }
            else if (buttons[$.uiLocale['common']['edit']] != undefined) {
                buttons[$.uiLocale['common']['edit']]();
            }

            return false;
        }
    });
}

function ShowMessage(text, type) {
    $("#messages").html(text);
}

//----------------------------------------------------------
// Searching & Grid actions
//----------------------------------------------------------

function ReloadGrid(gridId) {
    $("#" + gridId).jqGrid().trigger("reloadGrid")
}

function Search(formId, gridId, url, rowDataFunc, masterId) {
    var sidx = "";
    var sord = "";
    var page = 0;
    var rows = 10;
    var search = $("#" + formId + " input[name='search']").val();
    $("#" + gridId + "-view-more-button").css("display", "inherit");
    $('#' + gridId).setGridParam({ page: page });

    $.ajax({
        url: url,
        data: 'search=' + search + '&sidx=' + sidx + '&sord=' + sord + '&page=' + page + '&rows=' + rows + '&mode=3' + '&masterId=' + masterId,
        type: 'post',
        success:
                function (data, textStatus, XMLHttpRequest) {
                    var rowIds = $('#' + gridId).jqGrid('getDataIDs');
                    var i;
                    // iterate through the rows and delete each of them
                    for (i = 0, len = rowIds.length; i < len; i++) {
                        var row = rowIds[i];
                        $('#' + gridId).jqGrid('delRowData', row);
                    }

                    var addData = data["rows"];
                    for (i = 0; i < addData.length; i++)
                        $("#" + gridId).jqGrid('addRowData', addData[i]["id"], rowDataFunc(addData[i]), "last");

                    SetGridTotalCount(gridId, data.records);
                    HideMoreResults(gridId, data.records);
                },
        error:
                function (jqXHR, textStatus, errorThrown) {
                    document.location = errorPage;
                }
    });
}


function ClearAndSearch(formId, gridId, url, rowDataFunc, masterId) {
    ResetForm(formId);
    Search(formId, gridId, url, rowDataFunc, masterId);
}

function DeleteGridItem(gridId, url, itemId, masterId) {
    var settings = {
        title: $.uiLocale['deleteDialog']['title'],
        message: $.uiLocale['deleteDialog']['message'],
        funcOK: function () {
            var data = 'id=' + itemId;

            if (masterId != undefined)
                data = data + '&masterId=' + masterId;

            $.ajax({
                url: url,
                data: data,
                type: 'post',
                success:
                function (data, textStatus, XMLHttpRequest) {
                    ReloadGrid(gridId);
                },
                error:
                function (jqXHR, textStatus, errorThrown) {
                    ShowMessage(jqXHR.responseText);
                }
            });
        }
    };

    ConfirmDialog(settings);

    return false;
}

function RemoveDetailItem(gridId, url, itemId) {
    var settings = {
        title: $.uiLocale['removeDialog']['title'],
        message: $.uiLocale['removeDialog']['message'],
        funcOK: function () {
            $.ajax({
                url: url,
                data: 'id=' + itemId,
                type: 'post',
                success:
                    function (data, textStatus, XMLHttpRequest) {
                        ReloadGrid(gridId);
                    },
                error:
                    function (jqXHR, textStatus, errorThrown) {
                        document.location = errorPage;
                    }
            });
        }
    };

    ConfirmDialog(settings);

    return false;
}

function SetGridTotalCount(gridId, count) {
    $("#" + gridId + "-total-count").html(count);
}

function ViewMoreResults(gridId, url, rowDataFunc, initialPage, pageSize, masterId) {
    var sidx = "";
    var sord = "";
    var gridPage = $('#' + gridId).getGridParam('page');
    var page = gridPage == 0 ? initialPage + 1 : gridPage + 1;
    var rowNum = $('#' + gridId).getGridParam('rowNum');
    var rowDataLength = $('#' + gridId).jqGrid().getRowData().length

    if (rowNum < rowDataLength + pageSize)
        $('#' + gridId).setGridParam({ rowNum: rowDataLength + pageSize });

    $.ajax({
        url: url,
        data: 'sidx=' + sidx + '&sord=' + sord + '&page=' + page + '&rows=0&mode=2&masterId=' + masterId,
        type: 'post',
        success:
                function (data, textStatus, XMLHttpRequest) {
                    var addData = data["rows"];
                    for (var i = 0; i < addData.length; i++)
                        $("#" + gridId).jqGrid('addRowData', addData[i]["id"], rowDataFunc(addData[i]), "last");

                    $('#' + gridId).setGridParam({ page: page });
                    HideMoreResults(gridId, data.records);
                },
        error:
                function (jqXHR, textStatus, errorThrown) {
                    document.location = errorPage;
                }
    });
}

function ShowSelection(popUpId, agridId, sgridId, url, masterId) {
    $("#" + popUpId).css({ display: "inherit" });

    var settings = {
        title: $.uiLocale['selectionDialog']['title'],
        width: 700,
        popUpId: popUpId,
        openFunc: function () { ReloadGrid(agridId); },
        funcOK: function () {
            // catch elements
            var gridObj = $("#" + agridId).jqGrid();
            var gridIds = $(gridObj).getGridParam("selarrrow");
            var jsonIds = [];
            for (var i = 0; i < gridIds.length; i++)
                jsonIds.push(JSON.parse(parseInt(gridIds[i])));

            $.ajax({
                url: url,
                data: { ids: jsonIds, masterId: masterId },
                type: 'post',
                traditional: true,
                success:
                    function (data, textStatus, XMLHttpRequest) {
                        ReloadGrid(sgridId);
                    },
                error:
                    function (jqXHR, textStatus, errorThrown) {
                        document.location = errorPage;
                    }
            });
        }
    };

    SelectionPopUp(settings);

    return false;
}

function AddOrEditGridDetail(detailName, gridId, url, mode) {
    $("body").append('<div id="' + detailName + '-dialog"></div>');

    var settings = {
        title: $.uiLocale['common'][mode],
        popUpId: detailName + '-dialog',
        okText: $.uiLocale['common']['save'],
        width: 800,
        funcOK: function () {
            var form = $("#" + detailName + "-dialog").find('form:first')[0];
            $.ajax({
                url: url,
                data: $(form).serialize(),
                type: 'post',
                success:
                    function (data, textStatus, XMLHttpRequest) {
                        if (data == "OK") {
                            ReloadGrid(gridId);
                            $("#" + detailName + "-dialog").remove();
                        }
                        else {
                            WriteDetailPopUpContent(detailName, data, settings, url, true);
                        }
                    },
                error:
                    function (jqXHR, textStatus, errorThrown) {
                        //document.location = errorPage;
                    }
            });
        }
    };

    $.ajax({
        url: url,
        type: 'get',
        success:
            function (data, textStatus, XMLHttpRequest) {
                WriteDetailPopUpContent(detailName, data, settings, url);
            },
        error:
            function (jqXHR, textStatus, errorThrown) {
                document.location = errorPage;
            }
    });
}

function WriteDetailPopUpContent(detailName, data, settings, url, disableOpen) {
    // Adding the content of popup
    $("#" + detailName + "-dialog").html(data);

    // Setting popup form action
    var form = $("#" + detailName + "-dialog").find('form:first')[0];
    $(form).attr('action', url);
    // Renaming popup input IDs (to avoid duplicates in the page)
    $(form).find('input').each(function () {
        var currentId = $(this).attr('id');
        $(this).attr('id', detailName + currentId);
    });

    // Loading initial partial view scripts
    window[detailName + 'LoadScripts'](detailName);

    // Show popup
    if (!disableOpen) {
        GridDetailPopUp(settings);
    }
}

function GridDetailPopUp(settings) {
    var btns = {};

    var okText = settings['okText'] || $.uiLocale['common']['select'];
    btns[okText] = function () {
        if (settings["funcOK"] != undefined)
            settings["funcOK"]();
    };

    btns[$.uiLocale['common']['cancel']] = function () {
        if (settings["funcCancel"] != undefined)
            settings["funcCancel"]();
        $(this).remove();
    };

    var popUpId = settings['popUpId'];

    $('#' + popUpId).attr('title', settings['title']);

    $("#" + popUpId).dialog({
        resizable: false,
        modal: true,
        buttons: btns,
        open: function () {
            var okClass;

            if (okText == $.uiLocale['common']['save']) {
                okClass = 'save-button';
            }

            if (okText == $.uiLocale['common']['select']) {
                okClass = 'select-button';
            }

            $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                icons: { primary: okClass }
            });
            $(this).parent().find('.ui-dialog-buttonpane button:first-child').next().button({
                icons: { primary: 'close-button' }
            });

            $("#" + popUpId).parent().find(".ui-button").blur();

            if (settings['openFunc'] != undefined) {
                settings['openFunc']();
            };
        },
        width: settings['width'] || 300,
        close: function (ev, ui) {
            if (settings["funcCancel"] != undefined)
                settings["funcCancel"]();
            $(this).remove();
        }
    });
}

function HideMoreResults(gridId, records) {
    // Check if more pages are available
    var page = $("#" + gridId).jqGrid().getGridParam('page');
    var pageSize = 10;
    var hasMorePages = ((page + 1) * pageSize) < records;

    if (!hasMorePages)
        $("#" + gridId + "-view-more-button").css("display", "none");
}

function DefaultSearchEventTriggers(formId) {
    $("#" + formId).bind("keypress", function (e) {
        if (e.keyCode == 13) {
            $("#" + formId + " input[name='search']").click();
            return false;
        }
    });
}

function FixGridColumnSize(settings) {
    var gridId = settings['gridId'];
    var hasEdit = settings['hasEdit'];
    var hasDetails = settings['hasDetails'];
    var hasDelete = settings['hasDelete'];

    var lastIndex = $("#" + gridId + " .jqgfirstrow td").length - 1;

    $("#" + gridId + " .jqgfirstrow td").each(function (index, element) {
        $(this).attr('style', '');

        if (hasEdit && !hasDetails && index == lastIndex - 1) // edit col without details
        {
            $(this).addClass('grid-cell-edit');
        }

        if (hasEdit && hasDetails && index == lastIndex - 2) // edit col
        {
            $(this).addClass('grid-cell-edit');
        }

        if (hasDetails && index == lastIndex - 1) // details col
        {
            $(this).addClass('grid-cell-details');
        }

        if (hasDelete && index == lastIndex) // delete col
        {
            $(this).addClass('grid-cell-delete');
        }
    });
}

function FormatGridBooleanProperty(settings) {
    var name = settings['name'];
    var gridId = settings['gridID'];
    var rowId = settings['rowID'];
    var trueImg = settings['trueImg'];
    var falseImg = settings['falseImg'];

    var rowData = jQuery('#' + gridId).jqGrid('getRowData', rowId);
    var value = rowData[name];

    if (value == "1") {
        if (trueImg) {
            return '<img src="' + trueImg + '"/>';
        }
        else {
            return '&nbsp;';
        }
    }
    else if (value == "0") {
        if (falseImg) {
            return '<img src="' + falseImg + '"/>';
        }
        else {
            return '&nbsp;';
        }
    }
}